package com.example.springai.controller;

import com.example.springai.bean.ChatTypeEnum;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@RestController
@RequestMapping("/ai")
public class CustomerServiceController {

    @Autowired
    @Qualifier("serviceChatClient")
    private ChatClient chatClient;


    @Autowired
    @Qualifier("inDatabaseChatHistoryRepository")
    private com.example.springai.repository.ChatHistoryRepository ChatHistoryRepository;

    /**
     * 流式返回结果
     *
     * @param prompt 用户输入的提示词
     * @return 大模型处理结果
     */
    @GetMapping(value = "/service", produces = "text/html;charset=utf-8")
    public Flux<String> chatByClientStream(@RequestParam String prompt, @RequestParam String chatId) {

        // [1] 保存会话id到数据库
        ChatHistoryRepository.save(ChatTypeEnum.SERVICE.getValue(), chatId);

        // [3] 与大模型交互
        return chatClient.prompt()
                .user(prompt)
                .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream()
                .content();
    }


}
